package com.cy.demo.controller;

import com.cy.demo.pojo.Address;
import com.cy.demo.service.IAddressService;
import com.cy.demo.service.ICartService;
import com.cy.demo.utils.jsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("addresses")
@RestController
public class AddressController extends BaseController{

    @Autowired
    private IAddressService addressService;

    //添加新地址接口
    @RequestMapping("/add_new_address")
    public jsonResult<Void> addNewAddress(Address address,HttpSession session){

        int uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);

        addressService.addNewAddress(uid,username,address);

        return new jsonResult<>(OK);
    }

    //展示所有地址
    @RequestMapping({"/",""})
    public jsonResult<List<Address>> showAddresses(HttpSession session){
        List<Address> addressList = addressService.showAddressesByUid(getuidFromSession(session));

        return new jsonResult<>(addressList,OK);
    }

    //修改默认地址
    @RequestMapping("/set_default/{id}")
    public jsonResult<Void> setDefault(@PathVariable ("id") int aid, HttpSession session){

        addressService.setDefault(aid,getuidFromSession(session),getUsernameFromSession(session));

        return new jsonResult<>(OK);
    }

    //删除收货地址
    @RequestMapping("/delete/{id}")
    public jsonResult<Void> deleteAddress(@PathVariable("id") int aid,
                                           HttpSession session) throws Exception {
        addressService.deleteByAid(aid);

        return new jsonResult<>(OK);
    }

    //修改地址接口
    @RequestMapping("/update/{id}")
    public jsonResult<Void> updateAddress(Address address,
                                          @PathVariable("id") int aid,
                                          HttpSession session){

        address.setAid(aid);
        addressService.updateByAid(getUsernameFromSession(session),address);

        return new jsonResult<>(OK);
    }
}
